import { createRouter, createWebHistory } from 'vue-router';
import Test from '../views/test/index.vue';
import Login from '../views/login/login.vue';
import Navigation from '../views/navigation/navigation.vue';

// 假设这里有一个全局变量来存储登录状态，实际项目中可以使用更复杂的状态管理
let isLoggedIn = false;

// 导出一个函数来修改登录状态
export const setLoggedIn = value => {
  isLoggedIn = value;
};
const requireAuth = (to, from, next) => {
  isLoggedIn = sessionStorage.getItem('user') || localStorage.getItem('user') ? true : false;
  if (isLoggedIn) {
    next();
  } else {
    next('/');
  }
};
// 路由守卫，用于验证用户是否登录
const routes = [
  {
    path: '/',
    component: Login,
    // 当从 Navigation 页面返回时，重置登录状态
    beforeEnter: (to, from) => {
      if (from.path === '/navigation') {
        isLoggedIn = false;
      }
      return true;
    }
  },
  {
    path: '/test',
    component: Test
  },
  {
    path: '/navigation',
    component: Navigation,
    // 进入该路由前进行登录验证
    beforeEnter: requireAuth
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

export default router;
